import axios from "../../axios";
import { useEffect, useState } from "react";
import { Popconfirm, Upload, Image, InputNumber, Select, Input, Switch, Row, Col, Table, Button, message, Modal, Form } from "antd"
import { InboxOutlined, PlusOutlined } from '@ant-design/icons';

const { Search } = Input;
function Articletype() {
    const [selectList, setSelectList] = useState([// 下拉数据是静态的
        {
            value: -1,
            label: "全部"
        },
        {
            value: 1,
            label: "显示"
        },
        {
            value: 0,
            label: "不显示"
        }
    ])


    // 下拉
    const [selectValue, setSelectvalue] = useState("")
    const handleChanges = (value) => {
        // console.log(`${value}`);
        setSelectvalue(value)
    };
    // 搜索
    const [keywords, setkeywords] = useState("")
    const onSearch = (value) => {
        setkeywords(value)
    }
    // 下拉

    const [list, setList] = useState([

        // {
        //     id:100,
        //    name:"名字01",
        //    type:3,
        //    url:"空的",
        //    sort:0,
        //    status:true
        // },
        // {
        //     id:200,
        //    name:"名字01",
        //    type:3,
        //    url:"空的",
        //    sort:0,
        //    status:true
        // }
    ])
    const [page, setPage] = useState(1)
    const [limit, setLimit] = useState(20)
    const [total, settotal] = useState(0)
    const getList = async () => {

        let { list, total } = await axios.get("/category/list", {
            params: {
                // keywords,
                // cid: selectValue,
                // page,
                // limit,
                // temp: new Date().getTime(),
                name: keywords,
                pid: 0,
                status: selectValue,
                type: 3,
                temp: new Date().getTime()
            }
        })
        setList(list)
        settotal(total)
    }

    // 下面是表格分页事件

    const pageOnChange = (page, pageSize) => {
        setPage(page)
        setLimit(pageSize)
    }
    // 下面是表格

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
        },
        {
            title: '分类图标',
            dataIndex: 'url',
            key: 'url',
            render:(_,row)=><img src={row.url} alt="" />
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
        },

        {
            title: '操作',
            dataIndex: 'X',
            key: 'X',
            render: (_, row) => (<>
                <Button onClick={() => editorClick(row)} size="small" type="primary">编辑</Button>
                {/* <Button onClick={()=>delFun(row)} size="small">删除</Button> */}
                <Popconfirm
                    title="删除"
                    description="确定要删除吗?"
                    onConfirm={() => confirm(row)}
                >
                    <Button size="small" danger>删除</Button>
                </Popconfirm>
            </>)
        },

    ];
    const confirm = (row) => {
        let index = list.findIndex(item => item.id == row.id)
        setList(pre => {
            pre.splice(index, 1)
            return [...pre]
        })
        message.success('删除成功');
    };

    // 删除

    useEffect(() => {
        getList()
    }, [selectValue, keywords, page, limit])


    // 增加和编辑***********************
    // 增加按钮
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [title, settitle] = useState("增加");


    const handleCancel = () => {// 关闭弹框
        setIsModalOpen(false);
        setName("")
        setFileList([])
        setSort("")
        setChecked("")
        setrowid("")
    };
    const addClick = () => {// 增加按钮
        settitle("增加")
        setIsModalOpen(true);

        setName("")
        setFileList([])
        setSort(0)
        setChecked(true)
        setrowid("")
    }
    const [rowId, setrowid] = useState("")
    const editorClick = (row) => {//****编辑要回显***** */
        console.log(row);
        setrowid(row.id)
        settitle("编辑")
        setIsModalOpen(true);
        setName(row.name)
        setFileList([{ url: row.url }])
        setSort(row.sort)
        setChecked(row.status)
    }


    const addAxios = async (name, sort, status,url) => {
        let res = await axios.post(`category/save?name=${name}&sort=${sort}&status=${status}&url=${url}&pid=0&type=3`)
        getList()
        setIsModalOpen(false);
    }

    const editorAxios=async (name, sort, status,url,id)=>{
        let res = await axios.post(`/category/update?name=${name}&sort=${sort}&status=${status}&url=${url}&id=${id}&pid=0&type=3`)
        getList()
        setIsModalOpen(false);
    }
    const yesCommit = () => {
         
        if (title == "增加") {//增加请求
           let url=fileList[0].response?fileList[0].response.data.url:""
         
            addAxios(name, sort, checked,url)

        } else {//编辑请求  带id
          let url=fileList[0].url?fileList[0].url:(fileList[0].response?fileList[0].response.data.url:"")
          editorAxios(name, sort, checked,url,rowId);
             

        }

    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };


    // 上传之前的钩子
    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([]);// 存放图片的 数据
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    const handleChange = ({ fileList: newFileList }) => setFileList(newFileList);
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </button>
    );
    const [name, setName] = useState("")
    const [sort, setSort] = useState(0)

    const [checked, setChecked] = useState(true);      // 状态切换
    const switchChange = (value) => {
        setChecked(value)
    }
    return (
        <section>
            <Row gutter={20}>
                <Col span={5}>
                    <Select
                        style={{ width: 200 }}

                        onChange={handleChanges}
                        options={selectList}
                    />
                </Col>
                <Col span={10}>
                    <Search
                        placeholder="请输入关键词"
                        allowClear
                        enterButton="搜索"

                        onSearch={onSearch}
                    />
                </Col>
            </Row>

            <Button type="primary" onClick={addClick}>添加文章分类</Button>
            <Table rowKey="id" dataSource={list} columns={columns}
                pagination={{
                    pageSize: limit,
                    total,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    showTotal: (total) => `共${total}条数据`,
                    onChange: pageOnChange,
                    pageSizeOptions: [20, 40, 60, 80, 100]
                }}
            />
            {/* 下面是模态框 */}
            <Modal title={title} open={isModalOpen} footer={null} onCancel={handleCancel}>

                {/* <input  value={name} onChange={(e)=>setName(e.target.value)} /> */}


                <Input value={name} onChange={(e) => setName(e.target.value)} />



                <Upload
                    name="multipart"
                    action="https://api.java.crmeb.net/api/admin/upload/image?model=store&pid=0"
                    listType="picture-circle"
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>


                <InputNumber value={sort} onChange={(val) => setSort(val)} min={0} ></InputNumber>


                <Switch checked={checked} onChange={switchChange} />


                <Button type="primary" onClick={yesCommit}>
                    提交
                </Button>
            </Modal>

        </section>
    );
}

export default Articletype;